/**
 * 公共插件
 */
$.namespace("common.plugins.area");

/**
 * 区域选择插件
 *
 * 使用例子:
 * <pre>
 *     初始化:
 *     $("#categoryNameSearch").area({value:"110112",required:true,fullPath: true})
 *     使用函数---设置区域:
 *     $("#categoryNameSearch").area("setValue", "110112")
 *     使用函数---获取区域:
 *     $("#categoryNameSearch").area("getValue")
 *     使用函数---清空区域:
 *     $("#categoryNameSearch").area("clear")
 *
 *     还可以使用：$("#categoryNameSearch").val()获取区域编码
 *
 * </pre>
 *
 * @param opts [value:初始值, required:是否必填， fullPath: 是否需要精确到县]
 * @param paras 调用函数时是哦也能够参数
 * @returns {*}
 */
$.fn.area = function (opts, paras) {
    if (typeof opts == "string") {
        return $.fn.area.methods[opts]($(this), paras);
    } else {
        opts = opts || {};
        common.plugins.area.initArea(opts, $(this));
    }
};

$.fn.area.methods = {
    setValue: function(me, value) {
	    var options = me.data("options");
	    if (options.multiple) {
	    	codes = value.split(',');
	        var provinceCode = codes[0].substring(0, 2) + "0000";
	        var cityCode = codes[0].substring(0, 4) + "00";
	        common.plugins.area.selectProvince(provinceCode, me).done(function() {
	            common.plugins.area.selectCity(cityCode, me).done(function() {
	            	for (var i = 0; i < codes.length; i++) {
	            		common.plugins.area.selectCounty(codes[i], me);
	            		me.combo('hidePanel');
	            	}
	            });
	        });
	    } else {
	        var provinceCode = value.substring(0, 2) + "0000";
	        var cityCode = value.substring(0, 4) + "00";
	        var countyCode = value;

	        common.plugins.area.selectProvince(provinceCode, me).done(function() {
	            common.plugins.area.selectCity(cityCode, me).done(function() {
	                common.plugins.area.selectCounty(countyCode, me);
	            });
	        });
	    }
    },
    getValue: function(me) {
        return me.data("areaData");
    },
    clear: function(me) {
        var panel = me.combo('panel');
        var textbox = me.combo('textbox');
        me.val("");
        textbox.val("");
        panel.tabs('close', '城市');
        panel.tabs('close', '区县');
        panel.tabs('getTab', '省份').find(".selectSpan").removeClass("selectSpan");
    }
};

$.fn.area.methods.setData = function(me, data) {
    me.data("areaData", data);
    common.plugins.area.display(me);
};

common.plugins.area.initArea = function (opts, me) {
    var def = $.Deferred();
    me.val("");
    if (me.data("initFlag")) {
        return;
    }

    me.combo({
        width: me.width(),
        height: me.height(),
        panelWidth: me.width(),
        panelHeight: opts.height || 'auto',
        required: opts.required || false,
        disabled: opts.disabled,
        readonly: true,
        hasDownArrow: false,
        onShowPanel: function() {
            $(".tabs-tool").css("height", "23px");
        }

    });

    var textbox = me.combo('textbox');
	var tools = [{
	    iconCls: "icon-remove",
	    handler: function() {
	        me.area('clear');
	    }
	}];
	if (opts.multiple) {
	    tools.push({
	        iconCls: "icon-ok",
	        handler: function() {
	            me.combo('hidePanel');
	        }
	    });
	}
	var panel = me.combo('panel').tabs({
	    tools: tools
	});

    textbox.focus(function () {
        me.combo('showPanel');
    });

    panel.tabs('add', {
        id: 'provinceTag',
        title: '省份',
        href: $.ctx + "/common/area/next?code=000000&level=province",
        extractor: function (data) {
            data = $.parseJSON(data);
            return common.plugins.area.createTagPanel(data, "province", me);
        },
        onLoad: function() {
            def.resolve();
        }
    });

    opts.fullPath = opts.fullPath == null ? true : opts.fullPath;
    me.data("options", opts);

    me.data("initFlag", true);

    def.done(function() {
        if (opts.value != null) {
            me.area('setValue', opts.value);
        }
    });
};

common.plugins.area.selectProvince = function (code, me) {
    var def = $.Deferred();
    var panel = me.combo("panel");
    var cityTag = panel.find("#cityTag");
    var tab = panel.tabs("getTab", "省份");
    var url = $.ctx + "/common/area/next?code=" + code + "&level=city";
    var item = tab.find(".areaSpan_" + code);
    var name = item.children("a").html();

    if (item.length == 0) {
        def.reject();
        return def;
    }

    common.plugins.area.selectSpan(item);
    if (cityTag.length > 0) {
        cityTag.panel({
            href: url,
            extractor: function (data) {
                data = $.parseJSON(data);
                if (data.length == 0) {
                    var newData = [[code, name]];
                    me.data('areaData', newData);

                    panel.tabs('close', '城市');
                    panel.tabs('close', '区县');
                    common.plugins.area.display(me);
                    me.combo('hidePanel');
                    return;
                }
                return common.plugins.area.createTagPanel(data, "city", me);
            },
            onLoad: function() {
                def.resolve();
            }
        });
        panel.tabs('select', '城市');
        panel.tabs('close', '区县');
    } else {
        panel.tabs('add', {
            id: "cityTag",
            title: "城市",
            href: url,
            extractor: function (data) {
                data = $.parseJSON(data);
                if (data.length == 0) {
                    var newData = [[code, name]];
                    me.data('areaData', newData);

                    panel.tabs('close', '城市');
                    panel.tabs('close', '区县');
                    common.plugins.area.display(me);
                    me.combo('hidePanel');
                    return;
                }
                return common.plugins.area.createTagPanel(data, "city", me);
            },
            onLoad: function() {
                def.resolve();
            }
        });
    }

    var data = [[code, name]];
    me.data('areaData', data);

    var options = me.data("options");
    if (!options.fullPath) {
        common.plugins.area.display(me);
    }

    return def;
};

common.plugins.area.selectCity = function (code, me) {
    var def = $.Deferred();
    var panel = me.combo("panel");
    var countyTag = panel.find("#countyTag");
    var tab = panel.tabs("getTab", "城市");
    var url = $.ctx + "/common/area/next?code=" + code + "&level=county";
    var item = tab.find(".areaSpan_" + code);
    var name = item.children("a").html();

    if (item.length == 0) {
        def.reject();
        return def;
    }

    common.plugins.area.selectSpan(item);
    if (countyTag.length > 0) {
        countyTag.panel({
            href: url,
            extractor: function (data) {
                data = $.parseJSON(data);
                if (data.length == 0) {
//                    var newData = me.data('areaData');
//                    newData = [data[0], [code, name]];
//                    me.data('areaData', newData);
//
//                    panel.tabs('close', '区县');
//                    common.plugins.area.display(me);
//                    me.combo('hidePanel');
                	
	                  var newData = me.data('areaData');
	                  newData = [newData[0], [code, name]];
	                  me.data('areaData', newData);
	              
	                  panel.tabs('close', '区县');
	                  common.plugins.area.display(me);
	                  me.combo('hidePanel');
                } else {
                	  var newData = me.data('areaData');
	                  newData = [newData[0], [code, name]];
	                  me.data('areaData', newData);
	                  
					var options = me.data("options");
				    if (!options.fullPath) {
				        common.plugins.area.display(me);
				    }

                	return common.plugins.area.createTagPanel(data, "county", me);
                }
            },
            onLoad: function() {
                def.resolve();
            }
        });
        panel.tabs('select', '区县');
    } else {
        panel.tabs('add', {
            id: "countyTag",
            title: "区县",
            href: url,
            extractor: function (data) {
                data = $.parseJSON(data);
                if (data.length == 0) {
//                    var newData = me.data('areaData');
//                    newData = [data[0], [code, name]];
//                    me.data('areaData', newData);
//
//                    panel.tabs('close', '区县');
//                    common.plugins.area.display(me);
//                    me.combo('hidePanel');
                	
	                  var newData = me.data('areaData');
	                  newData = [newData[0], [code, name]];
	                  me.data('areaData', newData);
	              
	                  panel.tabs('close', '区县');
	                  common.plugins.area.display(me);
	                  me.combo('hidePanel');
                } else {
                	  var newData = me.data('areaData');
	                  newData = [newData[0], [code, name]];
	                  me.data('areaData', newData);
	                  
  
					    var options = me.data("options");
					    if (!options.fullPath) {
					        common.plugins.area.display(me);
					    }
              	return common.plugins.area.createTagPanel(data, "county", me);
                }
            },
            onLoad: function() {
                def.resolve();
            }
        })
    }

    return def;
};

common.plugins.area.selectCounty = function (code, me) {
    var panel = me.combo("panel");
    var tab = panel.tabs("getTab", "区县");
    var item = tab.find(".areaSpan_" + code);
    var name = item.children("a").html();

    if (item.length == 0) {
        return;
    }

    var options = me.data("options");
    if (options.multiple) {
        var data = me.data('areaData');
        if (!item.hasClass("selectSpan")) {
            if (!options.maxNum || item.parent().children(".selectSpan").length < options.maxNum) {
	            if (typeof data[2] == 'object') {
	                data[2][0].push(code);
	                data[2][1].push(name);
	            } else {
	                data[2] = [[code], [name]];
	            }
	            item.addClass("selectSpan");
	        }
        } else {
            if (item.parent().children(".selectSpan").length > 1) {
                if (typeof data[2] == 'object') {
                    data[2][0] = $.grep(data[2][0], function (el) {
                        return el !== code;
                    });
                    data[2][1] = $.grep(data[2][1], function (el) {
                        return el !== name;
                    });
                }
                item.removeClass("selectSpan");
            }
        }
        me.data('areaData', data);

        common.plugins.area.display(me);
    } else {
        common.plugins.area.selectSpan(item);
        var data = me.data('areaData');
        data = [data[0], data[1], [code, name]];
        me.data('areaData', data);

        common.plugins.area.display(me);
        me.combo('hidePanel');
    }
};

common.plugins.area.createTagPanel = function(data, level, me) {
    var clickFn;
    switch (level) {
        case "province" :
            clickFn = common.plugins.area.selectProvince;
            break;
        case "city" :
            clickFn = common.plugins.area.selectCity;
            break;
        case "county" :
            clickFn = common.plugins.area.selectCounty;
            break;
    }
    var outerDiv = $("<div></div>").addClass("tagContentOutterDiv");
    $.each(data, function (i, areaNode) {
        var areaSpan = $("<span></span>").addClass("areaSpan_" + areaNode.admareaCode).attr("title", areaNode.admareaName).appendTo(outerDiv);
        var areaLink = $("<a></a>").attr("href", "javascript:void(0)").click(function (item) {
            clickFn(areaNode.admareaCode, me, item, areaNode);
        }).appendTo(areaSpan);
        areaLink.html(areaNode.admareaName);
    });
    return outerDiv;
};

common.plugins.area.selectSpan = function(obj) {
    obj.parent().children(".selectSpan").removeClass("selectSpan");
    obj.addClass("selectSpan");
};

common.plugins.area.display = function(me) {
    var data = me.data('areaData');
    var textbox = me.combo('textbox');

    if (data) {
        try {
            var text = data.map(function (n) {
                 if (typeof n[1] == "string") {
                    return n[1];
                } else if (typeof n[1] == "object" || n[1].join) {
                    return n[1].join("/");
                }
            }).join(" ");
            var value = data.map(function (n) {
                if (typeof n[1] == "string") {
                    return n[1];
                } else if (typeof n[1] == "object" || n[1].join) {
                    return n[1].join("/");
                }
            }).join("/");
            textbox.val(text);
            me.val(value);
        } catch (e) {
            console.error("地区插件初始化数据错误");
        }
    }
};
